package com.bdqn.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * XML添加
 *
 * @author LILIBO
 * @since 2024/6/28
 */
public class Test03XmlAdd {

    public static void main(String[] args) {
        String xmlFile = "src/main/java/收藏信息.xml";
        // 创建XML文档解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            // 获得XML文档解析器
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 解析XML文件
            Document document = builder.parse(xmlFile);
            // 创建元素节点
            Element brandElement = document.createElement("Brand"); // <Brand></Brand>
            // 设置name属性的值
            brandElement.setAttribute("name", "魅族"); // <Brand name="魅族"></Brand>

            // 创建元素节点
            Element typeElement = document.createElement("Type"); // <Type></Type>
            typeElement.setAttribute("name", "XX001"); // <Type name="XX001"></Type>
            // 将子元素Type添加到新创建的Brand元素节点内
            brandElement.appendChild(typeElement); // <Brand name="魅族"><Type name="XX001"></Type></Brand>

            // 获取根节点
            Element phoneInfoElement = (Element) document.getElementsByTagName("PhoneInfo").item(0);
            // 将新创建的Brand元素节点添加到根节点内
            phoneInfoElement.appendChild(brandElement);

            // 创建一个空白的文本节点
            Text textNode = document.createTextNode("\t");
            phoneInfoElement.appendChild(textNode);

            System.out.println("Brand节点添加成功！");

            // 将创建好的XML保存
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(document);
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            StreamResult result = new StreamResult(Files.newOutputStream(Paths.get(xmlFile)));
            transformer.transform(domSource, result); // 保存
            System.out.println("XML文档保存成功！");
        } catch (ParserConfigurationException | IOException | SAXException | TransformerException e) {
            e.fillInStackTrace();
        }
    }

}
